package com.itheima.controller;

import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(
            @Pattern(regexp = "^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$",
                    message = "手机号格式不正确")
            String username,
            @Pattern(regexp = "^[a-zA-Z0-9_-]{4,16}$", message = "密码格式不正确")
            String password){
        System.out.println( username + "    " +  password);
        if(username == null || password == null){
            return Result.error("缺少必要的参数");
        }
        User registerUser = userService.findByUserName(username);
        if(registerUser != null){
            return Result.error("用户名已存在");
        }
        else {
            userService.register(username,password);
            return Result.success();
        }
    }
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$",
            message = "手机号格式不正确") String username, @Pattern(regexp = "^[a-zA-Z0-9_-]{4,16}$", message = "密码格式不正确")String password){
        User loginUser = userService.findByUserName(username);
        if(loginUser == null){
            return Result.error("用户未注册");
        }
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //生成token令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token, 1,TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/list")
    public Result<PageBean<User>> list(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize,
                                 @RequestParam(required = false) String username1,
                                 @RequestParam(required = false) String permission1,
                                 @RequestParam(required = false) String createTime1
                                 ){
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        if(userService.findByUserName(username).getPermission().equals("0")){
            PageBean<User> pageBean = userService.list(pageNum,pageSize,username1,permission1,createTime1);
            return Result.success(pageBean);
        }
        return Result.error("权限不足");
    }

    @PutMapping("/updatePermission")
    public Result updatePermission(@RequestParam("id") Integer id,
                                   @RequestParam("permission") String permission){
        System.out.println("✅ 收到请求：id=" + id + ", permission=" + permission);
        userService.updatePermission(id, permission);
        return Result.success();
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id){
        System.out.println("✅ 收到请求：id=" + id);
        userService.delete(id);
        return Result.success();
    }
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        // 根据用户名查询账户
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        System.out.println("✅ 收到请求：avatarUrl=" + avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map, @RequestHeader("Authorization") String token){
        //1. 校验参数
        String oldPassword = map.get("old_pwd");
        String newPassword = map.get("new_pwd");
        String RePassword = map.get("re_pwd");
        if(!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(newPassword) || !StringUtils.hasLength(RePassword)){
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User loginUser = userService.findByUserName(username);
        if(!Md5Util.getMD5String(oldPassword).equals(loginUser.getPassword())){
            return Result.error("原密码错误");
        }
        if(oldPassword.equals(newPassword)){
            return Result.error("新密码不能与原密码一致");
        }
        if(!newPassword.equals(RePassword)){
            return Result.error("两次密码不一致");
        }

        // 2.调用service，完成密码更新
        userService.updatePwd(newPassword);
        // 删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}


